package phone.qyg.com.qyg.fragment.course.detail;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.app.adapter.recycler.CommonAdapter;
import com.app.adapter.recycler.MultiItemTypeAdapter;
import com.app.adapter.recycler.RecyclerViewItemDecoration;
import com.app.adapter.recycler.base.ViewHolder;
import com.app.application.QXApplication;
import com.app.base.tool.BaseFragment;
import com.app.config.AppHttpKey;
import com.app.config.ApplicationConfig;
import com.app.utils.CommonUtil;
import com.app.utils.JSONTool;
import com.app.utils.PromptManager;
import com.app.utils.TransformController;
import com.app.view.BaseViewStateLayout;
import com.liaoinstan.springview.container.AliFooter;
import com.liaoinstan.springview.container.AliHeader;
import com.liaoinstan.springview.widget.SpringView;

import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import phone.qyg.com.qyg.R;
import phone.qyg.com.qyg.activity.CourseReleaseNoteActivity;
import phone.qyg.com.qyg.model.CourseInterTrans;
import phone.qyg.com.qyg.model.CourseNote;
import phone.qyg.com.qyg.model.Delete;
import phone.qyg.com.qyg.utils.AppHttpRequest;
import phone.qyg.com.qyg.utils.PopuDelete;

/**
 * 作者：lblbh on 2017/12/11 16:53
 * 邮箱：lanbuhan@163.com
 * 功能：笔记 使用问答布局
 */

public class NoteFragment extends BaseFragment {

    private static String courseID;//课程id

    @ViewInject(R.id.linear)
    RelativeLayout linear;

    BaseViewStateLayout baseView;

    RecyclerView recycler;

    CommonAdapter adapter;

    SpringView springview;

    List<CourseNote> models;

    boolean isForce;

    int page_no,totalpage;

    public static final NoteFragment newInstance(String courseID){
        NoteFragment fragment = new NoteFragment();
        Bundle bundle = new Bundle();
        bundle.putString(AppHttpKey.COURSE_ID, courseID);
        NoteFragment.courseID = courseID;
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public View initView(LayoutInflater inflater) {
        View view = View.inflate(QXApplication.getContext(), R.layout.course_interlocu,null);
        x.view().inject(this,view);
        return view;
    }


    @Override
    public void initData(Bundle savedInstanceState) {
        if (isRequestStr(courseID)) {
            courseID = getArguments().getString(AppHttpKey.COURSE_ID);
        }

        baseView = new BaseViewStateLayout(QXApplication.getContext()) {

            @Override
            public View obtionView() {
                View sucessView = View.inflate(QXApplication.getContext(), R.layout.base_spring_recycler,null);
                recycler = (RecyclerView) sucessView.findViewById(R.id.recycler);
                LinearLayoutManager layoutVerManager = new LinearLayoutManager(QXApplication.getContext());
                layoutVerManager.setOrientation(LinearLayoutManager.VERTICAL);
                recycler.addItemDecoration(new RecyclerViewItemDecoration(
                        RecyclerViewItemDecoration.MODE_HORIZONTAL, getResources().getColor(R.color.divider),
                        CommonUtil.dip2px(QXApplication.getContext(),1),0,0));
                recycler.setLayoutManager(layoutVerManager);

                springview = (SpringView) sucessView.findViewById(R.id.springview);

                springview.setListener(new SpringView.OnFreshListener() {
                    @Override
                    public void onRefresh() {
                        isForce = true;
                        getInitNetwork(false);
                    }

                    @Override
                    public void onLoadmore() {
                        if(isRequestList(models) && (page_no < totalpage) ){
                            getInitNetwork(true);
                        }else{
                            PromptManager.showToast(R.string.more_no_datas);
                            springview.onFinishFreshAndLoad();
                        }

                    }
                });

                springview.setHeader(new AliHeader(QXApplication.getContext(),false));
                springview.setFooter(new AliFooter(QXApplication.getContext(),false));
                return sucessView;
            }

            @Override
            public Object obtionData() {
                return DELFAUTSTATE;
            }
        };

        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        linear.addView(baseView,layoutParams);
        x.view().inject(linear);

        TextView addInterlocu = (TextView) View.inflate(QXApplication.getContext(),R.layout.course_add_interlocu,null);
        CommonUtil.setTextViewDrawableDirection(addInterlocu,4,R.drawable.detail_add_note);

        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
        params.bottomMargin = CommonUtil.dip2px(QXApplication.getContext(),100);
        params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        linear.addView(addInterlocu,1,params);
//        linear.addView();

        addInterlocu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //添加笔记
                CourseInterTrans trans = new CourseInterTrans(Integer.valueOf(courseID),0);
                TransformController.transformControllerModel(QXApplication.getContext(), CourseReleaseNoteActivity.class,trans);
            }
        });

        isSendNote();
    }

    private void isSendNote(){
        LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(QXApplication.getContext());
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ApplicationConfig.APP_QX_COURSE_NOTE);
        BroadcastReceiver mItemViewListClickReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                getInitNetwork(false);
            }
        };
        broadcastManager.registerReceiver(mItemViewListClickReceiver, intentFilter);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            //可见时执行的操作
            getInitNetwork(false);
        }
    }



    /**
     * 执行网络请求
     */
    private void getInitNetwork(final boolean isPull){

        if(isPull){
            page_no = page_no + 1;
        }else{
            page_no = 1;
        }

        if(isForce){
            page_no = 1;
        }

        fMapKeys.put(AppHttpKey.TYPE,"3");
        fMapKeys.put(AppHttpKey.COURSE_ID,courseID);
        fMapKeys.put(AppHttpKey.PAGE_NO,String.valueOf(page_no));
        AppHttpRequest.httpRequestDefalut(ApplicationConfig.COURSE_DETAIL,
                fMapKeys,
                new AppHttpRequest.OnAppHttpListener() {
                    @Override
                    public void onAppHttpState(boolean isState, String result) {
                        springview.onFinishFreshAndLoad();
                        if(isState && JSONTool.isStatus(result)){
                            List<CourseNote> temps = JSONTool.jsonDefaluTranClazzs(result,JSONTool.Enum.NOTE_LIST, CourseNote.class);

                            totalpage = JSONTool.requestJSONfindNameCount(result,JSONTool.Enum.DATA,JSONTool.Enum.TOTALPAGE);

                            if(!isRequestList(temps) && !isPull){
                                baseView.setThreadOrState(BaseViewStateLayout.BaseViewState.STATE_EMPTY);
                                baseView.stateView();
                                return;
                            }
                            //成功获取到数据
                            baseView.setThreadOrState(BaseViewStateLayout.BaseViewState.STATE_SUCESS);
                            baseView.stateView();

                            setModelData(isPull,temps);
                        }else{
                            baseView.setThreadOrState(BaseViewStateLayout.BaseViewState.STATE_ERROE);
                            baseView.stateView();
                        }
                    }
                });
    }

    private void setModelData(final boolean isPull, List<CourseNote> temps) {
        if ((adapter == null && isRequestList(temps)) || isForce) {
            isForce = false;

            //数据初始化工作
            models = temps;

            final CommonAdapter adapter = new CommonAdapter<CourseNote>(QXApplication.getContext(),R.layout.course_item_note,models) {
                @Override
                protected void convert(ViewHolder holder, CourseNote model, int position) {
                    holder.setText(R.id.item_address,model.create_date);
                    holder.setText(R.id.item_title,model.title);
                }
            };

            adapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                    CourseNote obj = (CourseNote) adapter.getData().get(position);
                    TransformController.transformControllerModel(QXApplication.getContext(),CourseReleaseNoteActivity.class,obj);
                }

                @Override
                public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {

                    final CourseNote itemNote = (CourseNote) adapter.getData().get(position);

                    PopuDelete.showPopuWinDeleteCourse(linear,
                            new Delete(QXApplication.getContext().getResources().getString(R.string.note_detele_title),""),
                            R.layout.popu_detele,
                            position,
                            new PopuDelete.DeleteState() {
                                @Override
                                public void state(boolean isSucess, int position) {
                                    if(isSucess){
                                        Map<String,String> mapKeys = new HashMap<String,String>();
                                        mapKeys.put(AppHttpKey.ID,String.valueOf(itemNote.id));

                                        AppHttpRequest.appQuitState(ApplicationConfig.DELETE_COURSE_NOTE,
                                                mapKeys,
                                                new AppHttpRequest.OnAppHttpListener() {
                                                    @Override
                                                    public void onAppHttpState(boolean isState, String result) {
                                                        if(isState){
                                                            PromptManager.showToast(R.string.note_detele_sucess);
                                                            isForce = true;
                                                            getInitNetwork(false);
                                                        }
                                                    }
                                                });

                                    }
                                }
                            });
                    return true;
                }
            });
            recycler.setAdapter(adapter);
        }

        if (isPull && isRequestList(models) && isRequestList(temps)) {
            //上拉加载数据
            models.addAll(temps);
        }

//        //刷新数据
        if (adapter != null)
            adapter.notifyDataSetChanged();
    }


    @Override
    public void onNetChange(int netMobile) {}
}
